﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.Collections.Specialized;
using System.Net.Sockets;
using System.IO;

/// <summary>
/// printGPRS 的摘要说明
/// </summary>
public class printGPRS
{
    
    public string partner = " ";//用户ID
    public string apiKey = " ";//apiKEY API 密钥


    public string machine_code = "111";//机器码 终端编号
    public string mKey = "111";//秘钥           终端密钥


    public string IPstr = "114.215.116.141"; //接口地址
    public string port = "8888";
   
  
    public string sign = "";
    public printGPRS()
	{
		//
		// TODO: 在此处添加构造函数逻辑
		//
	}

    public string SendGprsPrintContent(string text)
    {

        string ss = "";

        Dictionary<string, string> parameters = new Dictionary<string, string>();//加密参数列表
        parameters.Add("content", text);
        parameters.Add("machine_code", machine_code);
        parameters.Add("partner", partner);

        sign = getSign(parameters, apiKey, mKey); //签名
       
        //上传参数 ?partner=7&sign=AEFJJFDKLSFJKLDLK12JK129997& machine_code=ffjdkfjdkffywfernvuemei12j&content=test


        string postquery = "partner={0}&sign={1}&machine_code={2}&content={3}".Replace("{0}", partner).Replace("{1}", sign).Replace("{2}", machine_code).Replace("{3}", text);

        string sendMsg = "POST / HTTP/1.1\r\n" +
                        "Host: " + IPstr +":"+port+ "\r\n" +
                        "Content-Type: application/x-www-form-urlencoded\r\n" +
                        "Content-Length: " + postquery.Length.ToString()+ "\r\n\r\n"
                        + postquery;


        ///-----------------------------------------------------------------------------------------
        try
        {
            //WorkerMan接口服务器，使用socket传送数据                                          
            Socket mySocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            mySocket.Connect(IPstr, int.Parse(port));


            

            int ctLen = Encoding.UTF8.GetBytes(postquery).Length;

            byte[] buffer = Encoding.UTF8.GetBytes(string.Format(sendMsg, IPstr + ":" + port, ctLen, postquery));
            mySocket.Send(buffer, 0, buffer.Length, SocketFlags.None);



            //接收返回数据
            buffer = new byte[2048000];
            int n;
            MemoryStream ms = new MemoryStream();
            while ((n = mySocket.Receive(buffer, 0, buffer.Length, SocketFlags.None)) > 0)
            {
                ms.Write(buffer, 0, n);
                Array.Clear(buffer, 0, buffer.Length);
            }
            string result = Encoding.UTF8.GetString(ms.ToArray());
            ms.Close();
            mySocket.Shutdown(SocketShutdown.Both);
            mySocket.Close();



            ss = result+" &nbsp;<br/>"+DateTime.Now.ToString();
        }
        catch
        {



            ss = "error";
        
        
        }
        //-----------------------------------------------------------------------------------------------------
        
               


        return ss;



    }


     



    /// <summary>
    /// 创建本次调用的签名
    /// </summary>       
    /// <param name="parameters">parameters，参数列表</param>
    /// <param name="preKey">preKey，apikey的值</param>
    /// <param name="secKey">secKey，终端密钥的值</param>
    /// <returns>String，签名</returns>
    private static String getSign(IDictionary<string, string> parameters, string preKey, string secKey)
    {
        // 第一步：把字典按Key的字母顺序排序
        IDictionary<string, string> sortedParams = new SortedDictionary<string, string>(parameters);
        IEnumerator<KeyValuePair<string, string>> dem = sortedParams.GetEnumerator();

        // 第二步：把所有参数名和参数值串在一起
        StringBuilder query = new StringBuilder("");
        while (dem.MoveNext())
        {
            string key = dem.Current.Key;
            string value = dem.Current.Value;
            if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(value))
            {
                query.Append(key).Append(value);
            }
        }
        string source = query.ToString();
        source = preKey + source + secKey;
        //System.Console.Out.WriteLine("source:" + source);
        return System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5").ToUpper();
        //return MD5(source);
    }



}
